package com.ruoyi.linkage.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.pengjie.SnowflakeIdUtils;
import com.ruoyi.linkage.Dto.LinkageStrategyListDto;
import com.ruoyi.linkage.Vo.LinkageStrategyAddVo;
import com.ruoyi.linkage.Vo.LinkageStrategyUpdateVo;
import com.ruoyi.linkage.Vo.LinkageStrategyVo;
import com.ruoyi.linkage.domain.LinkageAction;
import com.ruoyi.linkage.mapper.LinkageActionMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.linkage.mapper.LinkageStrategyMapper;
import com.ruoyi.linkage.domain.LinkageStrategy;
import com.ruoyi.linkage.service.ILinkageStrategyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 联动策略Service业务层处理
 *
 * @author pengjie
 * @date 2023-12-20
 */
@Service
public class LinkageStrategyServiceImpl implements ILinkageStrategyService
{
    @Autowired
    private LinkageStrategyMapper linkageStrategyMapper;
    @Autowired
    private LinkageActionMapper linkageActionMapper;
    @Autowired
    private LinkageActionServiceImpl linkageActionService;




    /**
     * 查询联动策略
     *
     * @param linkageStrategyId 联动策略主键
     * @return 联动策略
     */
    @Override
    public LinkageStrategy selectLinkageStrategyByLinkageStrategyId(String linkageStrategyId)
    {
        return linkageStrategyMapper.selectLinkageStrategyByLinkageStrategyId(linkageStrategyId);
    }

    /**
     * 查询联动策略列表
     *
     * @param linkageStrategy 联动策略
     * @return 联动策略
     */
    @Override
    public List<LinkageStrategy> selectLinkageStrategyList(LinkageStrategy linkageStrategy)
    {

        return linkageStrategyMapper.selectLinkageStrategyList(linkageStrategy);
    }

    /**
     * 新增联动策略
     *
     * @param linkageStrategy 联动策略
     * @return 结果
     */
    @Override
    public int insertLinkageStrategy(LinkageStrategy linkageStrategy)
    {
        return linkageStrategyMapper.insertLinkageStrategy(linkageStrategy);
    }

    @Transactional
    @Override
    public int addLinkageStrategy(LinkageStrategyAddVo linkageStrategyAddVo) {
        LinkageStrategy linkageStrategy=new LinkageStrategy();
        BeanUtils.copyProperties(linkageStrategyAddVo,linkageStrategy);
        if (linkageStrategyAddVo.getAi().equals("1")){
            linkageStrategy.setIsAiLinkage(linkageStrategyAddVo.getAi());
        }
        linkageStrategy.setCreateByName(SecurityUtils.getUsername());
        linkageStrategy.setCreateAt(new Date());
        linkageStrategy.setCreateBy(SecurityUtils.getUserId().toString());
        linkageStrategy.setLinkageStrategyId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        linkageStrategy.setLinkageStatus("1");
        System.out.println(linkageStrategyAddVo);
        List<Integer> list = new ArrayList<>();
        if (linkageStrategyAddVo.getListVo()!=null){
            list=linkageStrategyAddVo.getListVo().stream().map(it->{
                        LinkageAction linkageAction =new LinkageAction();
                        linkageAction.setLinkageDeviceId(it.getLinkageDeviceId());
                        linkageAction.setLinkageDeviceName(it.getLinkageDeviceName());
                        linkageAction.setLinkageAction(it.getLinkageAction());
                        linkageAction.setLinkageAlarmContent(it.getLinkageAlarmContent());
                        BeanUtils.copyProperties(linkageStrategyAddVo,linkageAction);
                        linkageAction.setLinkageActionId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));

                        linkageStrategy.setLinkageDeviceId(it.getLinkageDeviceId());
                        linkageStrategy.setLinkageDeviceName(it.getLinkageDeviceName());
                        insertLinkageStrategy(linkageStrategy);

                        BeanUtils.copyProperties(linkageStrategy,linkageAction);
                        return linkageActionMapper.insertLinkageAction(linkageAction);
                    }
            ).collect(Collectors.toList());
        }else{
            insertLinkageStrategy(linkageStrategy);
            LinkageAction linkageAction =new LinkageAction();
//            linkageAction.setLinkageDeviceId(linkageStrategyAddVo.getLinkageDeviceId());
//            linkageAction.setLinkageDeviceName(linkageStrategyAddVo.getLinkageDeviceName());
//            linkageAction.setLinkageAction(linkageStrategyAddVo.getLinkageAction());
//            linkageAction.setLinkageAlarmContent(linkageStrategyAddVo.getLinkageAlarmContent());
            BeanUtils.copyProperties(linkageStrategyAddVo,linkageAction);
            linkageAction.setCreateByName(SecurityUtils.getUsername());
            linkageAction.setCreateAt(new Date());
            linkageAction.setCreateBy(SecurityUtils.getUserId().toString());
            linkageAction.setLinkageStrategyId(linkageStrategy.getLinkageStrategyId());
            linkageAction.setLinkageActionId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
            linkageActionMapper.insertLinkageAction(linkageAction);
            list.add(1);
        }
        return list.isEmpty()?0:1;
    }

    /**
     * 修改联动策略
     *
     * @param linkageStrategy 联动策略
     * @return 结果
     */
    @Override
    public int updateLinkageStrategy(LinkageStrategy linkageStrategy)
    {
        return linkageStrategyMapper.updateLinkageStrategy(linkageStrategy);
    }

    @Transactional
    @Override
    public int editLinkageStrategy(LinkageStrategyUpdateVo linkageStrategyUpdateVo) {
        LinkageStrategy linkageStrategy= new LinkageStrategy();
        if (linkageStrategyUpdateVo.getAi().equals("1")){
            linkageStrategy.setIsAiLinkage("1");
        }else {
            linkageStrategy.setIsAiLinkage("0");
        }
        BeanUtils.copyProperties(linkageStrategyUpdateVo,linkageStrategy);
        ArrayList<T> list= new ArrayList();
        int num=0;
        if (linkageStrategyUpdateVo.getListVo()!=null) {
             num= linkageStrategyUpdateVo.getListVo().size();
        }
            LinkageAction linkageAction=new LinkageAction();
            List<LinkageAction> linkageActionList=new ArrayList<>();
            for (int i=0;i<num;i++){
                String string= JSON.toJSONString(linkageStrategyUpdateVo.getListVo().get(i));
                if (i==0){
                    linkageAction= (LinkageAction) JSON.parseObject(string,LinkageAction.class);
                    linkageActionList.add(linkageAction);
                }else {
                    LinkageAction linkageAction1=new LinkageAction();
                    LinkageAction linkageAction2=new LinkageAction();
                    BeanUtils.copyProperties(linkageAction,linkageAction1);
                    linkageAction2= (LinkageAction) JSON.parseObject(string,LinkageAction.class);
                    linkageAction1.setLinkageAction(linkageAction2.getLinkageAction());
                    linkageAction1.setLinkageAlarmContent(linkageAction2.getLinkageAlarmContent());
                    linkageAction1.setLinkageDeviceId(linkageAction2.getLinkageDeviceId());
                    linkageAction1.setLinkageDeviceName(linkageAction2.getLinkageDeviceName());
                    linkageActionList.add(linkageAction1);
                }
            }
            int a=linkageStrategyMapper.updateLinkageStrategy(linkageStrategy);

            if (num==0){
                return a;
            }else {
                List<Integer> listId=linkageActionList.stream().map(it->{
                    if ("".equals(it.getLinkageActionId())){
                        it.setLinkageActionId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    }
                    return linkageActionMapper.updateLinkageAction(it);
                }).collect(Collectors.toList());
                return listId.isEmpty()?0:1;
            }

    }

    /**
     * 批量删除联动策略
     *
     * @param linkageStrategyIds 需要删除的联动策略主键
     * @return 结果
     */
    @Override
    public int deleteLinkageStrategyByLinkageStrategyIds(String[] linkageStrategyIds)
    {
        return linkageStrategyMapper.deleteLinkageStrategyByLinkageStrategyIds(linkageStrategyIds);
    }

    /**
     * 删除联动策略信息
     *
     * @param linkageStrategyId 联动策略主键
     * @return 结果
     */
    @Override
    public int deleteLinkageStrategyByLinkageStrategyId(String linkageStrategyId)
    {
        return linkageStrategyMapper.deleteLinkageStrategyByLinkageStrategyId(linkageStrategyId);
    }

    /**
     * 查找联动策略信息
     *
     * @param linkageStrategyVo
     * @return 结果
     */
    @Override
    public List<LinkageStrategy> selectLinkageStrategyListOrder(LinkageStrategyVo linkageStrategyVo)
    {
        List<LinkageStrategy> linkageStrategyList=linkageStrategyMapper.selectLinkageStrategyListOrder(linkageStrategyVo);
        List<LinkageStrategy> list = linkageStrategyList.stream().map(it->{
            LinkageAction linkageAction=new LinkageAction();
            linkageAction.setLinkageStrategyId(it.getLinkageStrategyId());
            it.setList(linkageActionService.selectLinkageActionList(linkageAction));
            return it;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 查询联动策略列表返回IPage
     */
    @Override
    public PageInfo<LinkageStrategy> selectPage(LinkageStrategyVo linkageStrategyVo) {
        IPage<LinkageStrategy> page = new Page<>(Integer.parseInt(linkageStrategyVo.getPageNum()),Integer.parseInt(linkageStrategyVo.getPageSize()));
        if ("".equals(linkageStrategyVo.getColumn()) || linkageStrategyVo.getColumn() ==null){
            linkageStrategyVo.setColumn("createAt");
        }else {
            String str=linkageStrategyVo.getColumn();
            System.out.println(linkageStrategyVo.getColumn());
            System.out.println(str);
            //修改驼峰命名为数据库列格式
            StringBuffer buf=new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (Character.isUpperCase(c)) {
                    buf.append('_');
                    buf.append(Character.toLowerCase(c));
                }else {
                    buf.append(c);
                }
            }
            linkageStrategyVo.setColumn(buf.toString());
        }

        List<LinkageStrategy> list=linkageStrategyMapper.selectLinkageStrategyListOrder(linkageStrategyVo);
        list.stream().map(it->{
            LinkageAction linkageAction =new LinkageAction();
            linkageAction.setLinkageStrategyId(it.getLinkageStrategyId());
            it.setList(linkageActionService.selectLinkageActionList(linkageAction));
            return it;
        }).collect(Collectors.toList());
        PageInfo<LinkageStrategy> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<LinkageStrategyListDto> getList(LinkageStrategyVo linkageStrategyVo) {
        LinkageStrategy linkageStrategy=new LinkageStrategy();
        if (linkageStrategyVo.getAi()=="0"){
            linkageStrategy.setIsAiLinkage("0");
        }else {
            linkageStrategy.setIsAiLinkage("1");
        }
        BeanUtils.copyProperties(linkageStrategyVo,linkageStrategy);
        List<LinkageStrategy> list=selectLinkageStrategyList(linkageStrategy);
        //PageHelper.startPage(Integer.parseInt(linkageStrategyVo.getPageNum()),Integer.parseInt(linkageStrategyVo.getPageSize()));
        //联动设备+触发动作
        List<LinkageStrategyListDto> dtoList=new ArrayList<>();
                list.stream().map(it->{
            LinkageAction linkageAction=new LinkageAction();
            linkageAction.setLinkageStrategyId(it.getLinkageStrategyId());
            List<LinkageAction> linkageActionLIst=linkageActionService.selectLinkageActionList(linkageAction);
            linkageActionLIst.stream().map(at->{
                LinkageStrategyListDto dto=new LinkageStrategyListDto();
                dto.setLinkageDeviceNameAndAction(at.getLinkageDeviceName()+"    "+at.getLinkageAction());
                BeanUtils.copyProperties(it,dto);
                dtoList.add(dto);
                return at;
            }).collect(Collectors.toList());
            return it;
        }).collect(Collectors.toList());
//        TableDataInfo rspData = new TableDataInfo();
//        Page<LinkageStrategyListDto> pageInfo=new Page<>(dtoList,Integer.parseInt(linkageStrategyVo.getPageNum()),Integer.parseInt(linkageStrategyVo.getPageSize()));
//        rspData.setCode(HttpStatus.SUCCESS);
//        rspData.setMsg("查询成功");
//        rspData.setRows(dtoList);
//        rspData.setTotal(pageInfo.getTotal());
//        System.out.println(rspData.getTotal());
//        System.out.println(new PageInfo(dtoList));
        return dtoList;
    }
}
////是否查询所有
//        if ("".equals(linkageStrategyVo.getLinkageStrategyName())){
//                if (linkageStrategyVo.getOrder().equals("desc")){
//                queryWrapper.eq("is_ai_linkage",linkageStrategyVo.getAi()).orderByDesc(linkageStrategyVo.getColumn());
//                }
//                if (linkageStrategyVo.getOrder().equals("asc")){
//                queryWrapper.eq("is_ai_linkage",linkageStrategyVo.getAi()).orderByAsc(linkageStrategyVo.getColumn());
//                }
//                }else {
//                queryWrapper.like("linkage_strategy_name","%"+linkageStrategyVo.getLinkageStrategyName()+"%")
//                .eq("is_ai_linkage",linkageStrategyVo.getAi());
//                if (linkageStrategyVo.getOrder().equals("desc")){
//                queryWrapper.orderByDesc(linkageStrategyVo.getColumn());
//                }
//                if (linkageStrategyVo.getOrder().equals("asc")){
//                queryWrapper.orderByAsc(linkageStrategyVo.getColumn());
//                }
//                }
//                IPage<LinkageStrategy> linkageStrategyIPage=linkageStrategyMapper.selectPage(page,queryWrapper);
//        List<LinkageStrategy> list=linkageStrategyIPage.getRecords();
//        list.stream().map(it->{
//        LinkageAction linkageAction =new LinkageAction();
//        linkageAction.setLinkageStrategyId(it.getLinkageStrategyId());
//        it.setList(linkageActionService.selectLinkageActionList(linkageAction));
//        return it;
//        }).collect(Collectors.toList());
//        linkageStrategyIPage.setRecords(list);
//        return linkageStrategyIPage;
